//
//  LGPhotoPickerView.m
//  LGSanofiPatient
//
//  Created by 1234 on 2023/1/12.
//

#import "LGPhotoPickerView.h"
#import "LGPhotoPickerCell.h"
#import "HXCustomNavigationController.h"
#import "HXPhotoManager.h"
#import "HXPhotoModel.h"
#import "LGPhotoWayView.h"//选择照片方式弹框

#import <AssetsLibrary/AssetsLibrary.h>
#import "LQImgPickerActionSheet.h"
//#import "JJPhotoManeger.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImagePickerController.h"
#import "TZImageManager.h"
#import "TZVideoPlayerController.h"
#import "TZPhotoPreviewController.h"
#import "TZGifPhotoPreviewController.h"
#import "TZLocationManager.h"
#import "SDPhotoBrowser.h"
@interface LGPhotoPickerView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,JJPhotoDelegate,UIActionSheetDelegate,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UIAlertViewDelegate,UINavigationControllerDelegate,HXCustomNavigationControllerDelegate,SDPhotoBrowserDelegate>

@property (nonatomic , assign)BOOL isSelectOriginalPhoto;
@property (nonatomic , assign)CGFloat itemWH;
@property (nonatomic , assign)CGFloat margin;
/**   */
@property (nonatomic , strong)HXPhotoManager *manager;

@property (nonatomic , strong)CLLocation *location;
/**   */
@property (nonatomic , strong)NSMutableArray <HXPhotoModel*> *modelArray;


@end
static NSString * const reuseIdentifier = @"LQPhotoViewCell";

@implementation LGPhotoPickerView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.maxCount = 10;
        self.modelArray = [NSMutableArray array];
        self.addImageArray = [NSMutableArray array];
        self.allImageArray = [NSMutableArray array];
        self.urlArray = [NSMutableArray array];
        self.itemWH = (frame.size.width)/4.0;
        [self addSubview:self.collectionView];
        if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusNotDetermined) {
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                
            }];
        }
    }
    return self;
}

-(void)setMaxCount:(NSInteger)maxCount{
    _maxCount = maxCount;
    self.manager.configuration.maxNum = maxCount;
    [self.collectionView reloadData];
}

-(void)setItemWH:(CGFloat)itemWH{
    _itemWH = itemWH;
    [self.collectionView reloadData];
}

-(void)setUrlArray:(NSMutableArray *)urlArray{
    _urlArray = urlArray;
    self.modelArray = [NSMutableArray array];
    for (NSInteger i=0; i<urlArray.count; i++) {
        HXPhotoModel *model = [[HXPhotoModel alloc]init];
        model.imageURL = [NSURL URLWithString:urlArray[i]];
        [self.modelArray addObject:model];
        __weak typeof(self) weakSelf = self;
        [[SDWebImageManager sharedManager] loadImageWithURL:model.imageURL options:SDWebImageLowPriority progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
            [weakSelf.allImageArray addObject:image];
        }];
    }
    [self.collectionView reloadData];
    [self changeCollectionViewHeight];
}

-(void)setAddImageArray:(NSMutableArray *)addImageArray{
    _addImageArray = addImageArray;
    for (NSInteger i=0; i<addImageArray.count; i++) {
        HXPhotoModel *model = [[HXPhotoModel alloc]init];
        model.thumbPhoto  = addImageArray[i];
        [self.modelArray addObject:model];
    }
    [self.collectionView reloadData];
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if(self.modelArray.count < self.maxCount){
        return self.modelArray.count+1;
    }else{
        return self.modelArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    // Set up the reuse identifier
    LGPhotoPickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier: @"LGPhotoPickerCell" forIndexPath:indexPath];
    if (self.modelArray.count < self.maxCount && indexPath.row == self.modelArray.count) {
        [cell.photoView setImage:[UIImage imageNamed:@"上传图片-添加"]];
        cell.deleteBtn.hidden = YES;
    }else{
//        [cell.profilePhoto setImage:self.smallImageArray[indexPath.item]];
        cell.deleteBtn.hidden = NO;
        cell.model = self.modelArray[indexPath.item];
    }
    cell.deleteBtn.tag = [indexPath item];
    [cell.deleteBtn addTarget:self action:@selector(deletePhoto:) forControlEvents:UIControlEventTouchUpInside];
//    [self changeCollectionViewHeight];
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.item == self.modelArray.count){
        //添加图片
        [self addNewImage];
        
    }else{
        //查看大图
        SDPhotoBrowser *photoBrowser =[[SDPhotoBrowser alloc] init];
        photoBrowser.currentImageIndex = indexPath.item;
        photoBrowser.delegate = self;
        photoBrowser.imageCount = self.modelArray.count;
        photoBrowser.sourceImagesContainerView = self.collectionView;
        [photoBrowser show];
//        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:self.selectedAssetArray selectedPhotos:self.smallImageArray index:indexPath.item];
//        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
//        __weak typeof(self) weakSelf = self;
//        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//            weakSelf.smallImageArray = [NSMutableArray arrayWithArray:photos];
//            weakSelf.selectedAssetArray = [NSMutableArray arrayWithArray:assets];
//            weakSelf.isSelectOriginalPhoto = isSelectOriginalPhoto;
//            [weakSelf.collectionView reloadData];
//            weakSelf.collectionView.contentSize = CGSizeMake(0, ((weakSelf.smallImageArray.count + 2) / 3 ) * (weakSelf.margin + weakSelf.itemWH));
//        }];
//        [[self getViewController] presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index{
    // 不建议用此种方式获取小图，这里只是为了简单实现展示而已
    HXPhotoModel *model = self.modelArray[index];
    if(model.thumbPhoto){
        return model.thumbPhoto;
    }else{
        return [UIImage imageWithData:[NSData dataWithContentsOfURL:model.imageURL]];
    }
}

//// 返回高质量图片的url
//- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index{
//    return [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.picArray[index]]];
//}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(self.itemWH,self.itemWH);
}


#pragma mark - 选择图片
- (void)addNewImage{
    if (self.smallImageArray.count == self.maxCount) {
        [LGAlertTool singleActionAlertWithTitle:@"选择图片数量已达上限" sureAction:nil];
        return;
    }
    
    LGPhotoWayView *wayView = [[LGPhotoWayView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
    [[UIApplication sharedApplication].keyWindow addSubview:wayView];
    __weak typeof(self) weakSelf = self;
    wayView.LGSelectPhotoWay = ^(NSString * _Nonnull selectWay) {
        if([selectWay isEqualToString:@"camera"]){
            //相机-拍摄
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                UIImagePickerController *pickController = [[UIImagePickerController alloc]init];
                pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
                pickController.delegate = self;
                pickController.allowsEditing = YES;
                pickController.modalPresentationStyle = UIModalPresentationFullScreen;
                [[weakSelf getViewController] presentViewController:pickController animated:YES completion:nil];
            }
        }else{
            //相册
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.manager delegate:self];
                nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
                nav.modalPresentationCapturesStatusBarAppearance = YES;
                [[weakSelf getViewController] presentViewController:nav animated:YES completion:nil];
            }
        }
    };
}

//相册选完图片
- (void)photoNavigationViewController:(HXCustomNavigationController *)photoNavigationViewController didDoneAllList:(NSArray<HXPhotoModel *> *)allList photos:(NSArray<HXPhotoModel *> *)photoList videos:(NSArray<HXPhotoModel *> *)videoList original:(BOOL)original{
    if(photoList.count>0){
        self.modelArray = [NSMutableArray array];
        self.addImageArray = [NSMutableArray array];
        self.allImageArray = [NSMutableArray array];
        [self setUrlArray:self.urlArray];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (HXPhotoModel *model in photoList) {
            [self.modelArray addObject:model];
            [self.addImageArray addObject:model.thumbPhoto];
            [self.allImageArray addObject:model.thumbPhoto];
        }
        [self delegateReturnAction];
    }
    [self.collectionView reloadData];
    [self changeCollectionViewHeight];
    NSLog(@">>>??>>%d",original);
}

//代理返回
-(void)delegateReturnAction{
    if(self.delegate && [self.delegate respondsToSelector:@selector(addImagePickerChanged:)]){
        [self.delegate addImagePickerChanged:self.addImageArray];
    }
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(allImagePickerChanged:)]){
        [self.delegate addImagePickerChanged:self.allImageArray];
    }
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(modelImagePickerChanged:)]){
        [self.delegate modelImagePickerChanged:self.modelArray];
    }
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(addImagePickerChanged:tagString:)]){
        [self.delegate addImagePickerChanged:self.addImageArray tagString:self.tagString];
    }
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(allImagePickerChanged:tagString:)]){
        [self.delegate addImagePickerChanged:self.allImageArray tagString:self.tagString];
    }
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(modelImagePickerChanged:tagString:)]){
        [self.delegate modelImagePickerChanged:self.modelArray tagString:self.tagString];
    }
}

#pragma mark - TZImagePickerController
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSLog(@"%@",self.location);
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image location:self.location completion:^(NSError *error){
            if (error) {
                [tzImagePickerVc hideProgressHUD];
                NSLog(@"图片保存失败 %@",error);
            } else {
                [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES completion:^(TZAlbumModel *model) {
                    [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                        [tzImagePickerVc hideProgressHUD];
                        TZAssetModel *assetModel = [models firstObject];
                        if (tzImagePickerVc.sortAscendingByModificationDate) {
                            assetModel = [models lastObject];
                        }
                        [self refreshCollectionViewWithAddedAsset:assetModel.asset image:image];
                    }];
                }];
            }
        }];
    }
}

//拍照返回的图片
- (void)refreshCollectionViewWithAddedAsset:(id)asset image:(UIImage *)image{
    [self.selectedAssetArray addObject:asset];
    [self.addImageArray addObject:image];
    [self.allImageArray addObject:image];
    HXPhotoModel *model = [[HXPhotoModel alloc]init];
    model.thumbPhoto = image;
    model.previewPhoto = image;
    model.asset = asset;
    model.imageSize = image.size;
    model.type = HXPhotoModelMediaTypePhoto;
    [self.modelArray addObject:model];
    [self.manager afterSelectedListAddPhotoModel:model];
    [self.collectionView reloadData];
    [self delegateReturnAction];
    [self changeCollectionViewHeight];
    
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = asset;
        NSLog(@"location:%@",phAsset.location);
    }
}

#pragma mark - 删除照片
- (void)deletePhoto:(UIButton *)sender{
    HXPhotoModel *model = self.modelArray[sender.tag];
    [self.modelArray removeObjectAtIndex:sender.tag];
    [self.allImageArray removeObjectAtIndex:sender.tag];
    if(model.imageURL){
        [self.urlArray removeObjectAtIndex:sender.tag];
    }else{
        [self.addImageArray removeObjectAtIndex:sender.tag-self.urlArray.count];
        [self.selectedAssetArray removeObjectAtIndex:sender.tag];
    }
    [self.manager afterSelectedListdeletePhotoModel:model];//afterSelectedListdeletePhotoModel
//    [self.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:sender.tag inSection:0]]];
//    for (NSInteger item = sender.tag; item <= self.smallImageArray.count; item++) {
//        LGPhotoPickerCell *cell = (LGPhotoPickerCell*)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:item inSection:0]];
//        cell.deleteBtn.tag--;
//        cell.photoView.tag--;
//    }
    [self.collectionView reloadData];
    [self delegateReturnAction];
    [self changeCollectionViewHeight];
}


#pragma mark - 改变view，collectionView高度
- (void)changeCollectionViewHeight{
    self.itemWH = self.bounds.size.width/4.0;
    CGFloat height = (self.modelArray.count/4 +1)*self.itemWH;
    self.collectionView.frame = CGRectMake(0, 0, self.bounds.size.width, height);
    if(self.delegate && [self.delegate respondsToSelector:@selector(imagePickerHeightChanged:)]){
        [self.delegate imagePickerHeightChanged:height];
    }
}

#pragma mark - 获得选中图片各个尺寸
-(NSMutableArray *)getALAssetArray{
    return self.selectedAssetArray;
}

-(NSMutableArray *)getBigImageArray{
    self.bigImageArray = [NSMutableArray array];
    for (UIImage *ima in self.smallImageArray) {
        [self.bigImageArray addObject:ima];
    }
    return self.bigImageArray;
}

-(NSMutableArray *)getSmallImageArray{
    return self.smallImageArray;
}

-(NSMutableArray *)getUrlArray{
    return self.urlArray;
}

- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)layoutSubviews{
    [super layoutSubviews];
    [self changeCollectionViewHeight];
}


- (HXPhotoManager *)manager{
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _manager.configuration.requestImageAfterFinishingSelection = YES;
        _manager.configuration.languageType = HXPhotoLanguageTypeSc;
        _manager.configuration.type = HXConfigurationTypeWXChat;
        _manager.configuration.singleSelected = NO;
        _manager.configuration.photoCanEdit = NO;
    }
    return _manager;
}

-(UICollectionView *)collectionView{
    if(!_collectionView){
        UICollectionViewFlowLayout *layout= [[UICollectionViewFlowLayout alloc]init];
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) collectionViewLayout:layout];
        [_collectionView registerClass:[LGPhotoPickerCell class] forCellWithReuseIdentifier:@"LGPhotoPickerCell"];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.scrollEnabled = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;
}

-(NSMutableArray *)smallImageArray{
    if(!_smallImageArray){
        _smallImageArray = [NSMutableArray array];
    }
    return _smallImageArray;
}

-(NSMutableArray *)bigImageArray{
    if(!_bigImageArray){
        _bigImageArray = [NSMutableArray array];
    }
    return _bigImageArray;
}

-(NSMutableArray *)modelArray{
    if(!_modelArray){
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

-(NSMutableArray *)allImageArray{
    if(!_allImageArray){
        _allImageArray = [NSMutableArray array];
    }
    return _allImageArray;
}



@end
